package com.example.qzzm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.util.Linkify;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class TestActivity extends Activity {

	String mText = "<p><font color='#ff0000'>提前一天预约</font>，预约电话：025-85678922， 85689099</p><p><font color='#ff0000'>需一次体验完毕</font></p>";

	/**
	 * \ 思路 ： 1.找到一个电话号码 2.找到它的前后位置 3.截取它前面的html标签 4.截取它后面的html标签 5.组合成新的string
	 * 6.添加点击响应事件
	 * 
	 * 
	 * 重复1-6，直到找不到
	 */

	// 存储电话号码的TextView
	private List<Holder> pTextViews = new ArrayList<Holder>();

	// 除去电话号码的字符串
	private List<TextView> allTexts = new ArrayList<TextView>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);

		FrameLayout rLayout = (FrameLayout) findViewById(R.id.rl_test);

		// 方法3
		rLayout.addView(method3());
		// 方法2
		// rLayout.addView(method2());
		// 方法1
		// method1(rLayout);
	}

	/**
	 * 自定義的
	 * 
	 * @param v
	 */
	private void method1(ViewGroup v) {
		// TODO Auto-generated method stub
		getAllPhoneTags();
		spiltText();

		for (TextView tView : allTexts) {
			v.addView(tView);
		}
	}

	/**
	 * 返回TextView的List
	 */
	private void spiltText() {
		// 先将分界点加入allPositionsIntegers
		/** 将List按 前向位置排序 **/
		Comparator comp = new SortComparator();
		Collections.sort(pTextViews, comp);
		Collections.reverse(pTextViews);

		/**
		 * 加入首尾的
		 */
		int prePosition = pTextViews.get(0).prePosition;
		int lastPosition = pTextViews.get(pTextViews.size() - 1).leftPosition;
		String preString = mText.substring(0, prePosition);
		String lastString = mText.substring(lastPosition);
		pTextViews.add(new Holder(preString, 0, prePosition, 0));
		pTextViews.add(new Holder(lastString, lastPosition, mText.length() - 1,
				0));
		Collections.sort(pTextViews, comp);
		Collections.reverse(pTextViews);
		System.out.println(Arrays.toString(pTextViews.toArray()));
		/**
		 * 加入中间的
		 */
		List<Holder> temoHolders = new ArrayList<TestActivity.Holder>();
		temoHolders.addAll(pTextViews);
		Holder fHolder = temoHolders.get(0);
		System.out.println(fHolder.toString());

		for (Holder h : temoHolders) {
			if (h.prePosition <= fHolder.leftPosition) {
				fHolder = h;
				continue;
			}
			pTextViews.add(new Holder(mText.substring(fHolder.leftPosition,
					h.prePosition), fHolder.leftPosition, h.prePosition, 0));
			fHolder = h;
		}

		Collections.sort(pTextViews, comp);
		Collections.reverse(pTextViews);

		/**
		 * 遍历寻找标签
		 * 
		 * 添加到alltexts中
		 */
		for (Holder pi : pTextViews) {
			int from = pi.prePosition;
			int to = pi.leftPosition;

			String subString = pi.text;
			String pSubString = mText.substring(0, from);
			String lSubString = mText.substring(to, mText.length());

			subString = addTags(subString, pSubString, 0);
			subString = addTags(subString, lSubString, 1);

			TextView textView = new TextView(this);
			textView.setText(Html.fromHtml(subString));

			final String mString = pi.text;

			if (pi.Tag == 1) {
				textView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Toast.makeText(TestActivity.this, "你点击了电话号" + mString,
								Toast.LENGTH_SHORT).show();
					}
				});
			}
			allTexts.add(textView);
		}
	}

	/**
	 * 1.查找所有电话号码
	 */
	private void getAllPhoneTags() {
		String reg1 = "(025-){0,1}[0-9]{8}";

		Pattern p1 = Pattern.compile(reg1);
		Matcher matcher1 = p1.matcher(mText);
		while (matcher1.find()) {
			String phoneString = matcher1.group();
			int pPosition = matcher1.start();
			int lPosition = matcher1.end();
			pTextViews.add(new Holder(phoneString, pPosition, lPosition, 1));
		}
	}

	/**
	 * 对List排序
	 * 
	 * @author Administrator
	 *
	 */
	class SortComparator implements Comparator {
		@Override
		public int compare(Object lhs, Object rhs) {
			Holder a = (Holder) lhs;
			Holder b = (Holder) rhs;

			return (b.prePosition - a.prePosition);
		}
	}

	/**
	 * 查找html标签 并增加给h
	 * 
	 * @param h
	 * @param pString
	 */
	private String findHtmlTags(String childString) {
		String reg = "<[^>]*>";
		Pattern p = Pattern.compile(reg);
		StringBuffer sb1 = new StringBuffer();
		Matcher matcher1 = p.matcher(childString);
		while (matcher1.find()) {
			sb1.append(matcher1.group());
		}
		return sb1.toString();
	}

	/**
	 * 向Stringsh上添加标签
	 * 
	 * @param parentString
	 *            被添加的字符串
	 * @param childString
	 *            标签所在的字符串
	 * @param dir
	 *            方向
	 */
	private String addTags(String parentString, String childString, int dir) {
		if (dir == 0) {
			// 前面
			parentString = findHtmlTags(childString) + parentString;
		} else if (dir == 1) {
			// 后面
			parentString = parentString + findHtmlTags(childString);
		}
		return parentString;
	}

	class Holder {
		public String text;//
		public int prePosition;// 前面的位置
		public int leftPosition;// 后面的位置

		public int Tag;// 是否为目标

		public Holder(String textView, int prePosition, int leftPosition,
				int tag) {
			super();
			this.text = textView;
			this.prePosition = prePosition;
			this.leftPosition = leftPosition;
			this.Tag = tag;
		}

		@Override
		public String toString() {
			return "[" + prePosition + "," + leftPosition + "]";
		}
	}

	private TextView method2() {
		getAllPhoneTags();
		System.out.println(Arrays.toString(pTextViews.toArray()));
		TextView textView = new TextView(this);
		textView.setMovementMethod(LinkMovementMethod.getInstance());
		textView.setText(Html.fromHtml(addClickablePart(mText).toString()));
		return textView;
	}

	private CharSequence addClickablePart(String pTextViews2) {
		SpannableString spanStr = new SpannableString("");
		SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
		ssb.append(pTextViews2);

		for (Holder h : pTextViews) {
			final String text = h.text;
			final int start = mText.indexOf(h.text);
			if (start == -1) {
				continue;
			}
			ssb.setSpan(new ClickableSpan() {

				@Override
				public void onClick(View widget) {
					// TODO Auto-generated method stub
					Toast.makeText(TestActivity.this, "你点击了电话号" + text,
							Toast.LENGTH_SHORT).show();
				}
			}, start, start + text.length(), 0);

		}

		return ssb;
	}

	/**
	 * 最简单的方法：添加<a>标签
	 */
	private TextView method3() {
		getAllPhoneTags();

		for (Holder h : pTextViews) {
			final int start = mText.indexOf(h.text);
			String sub1 = mText.substring(0, start);
			String sub2 = mText.substring(start + h.text.length(),
					mText.length());
			mText = sub1;
			mText += "<a href='tel:" + h.text + "'>";
			mText += h.text;
			mText += "</a>";
			mText += sub2;
		}
		TextView textView = new TextView(this);
		textView.setAutoLinkMask(Linkify.ALL);
		textView.setMovementMethod(LinkMovementMethod.getInstance());
		textView.setFocusable(false);
		textView.setClickable(false);
		textView.setLongClickable(false);
		textView.setLinksClickable(true);
		textView.setText(Html.fromHtml(mText));
		return textView;
	}
}
